package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.WxArticle;
import cn.com.dashihui.web.service.WxArticleService;

@RequiresAuthentication
public class WxArticleController extends BaseController{
	private WxArticleService service = new WxArticleService();

    public void index(){
        render("index.jsp");
    }

	public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		//关键字
		String keyword = getPara("keyword");
		//添加时间范围
		String beginDate = getPara("beginDate");
		String endDate = getPara("endDate");
		//分类
		int categoryid = getParaToInt("categoryid",0);
		/*//是否置顶
		String isTop = getPara("isTop");*/
		//int mp = getParaToInt("mp");
		renderResult(0,service.findByPage(pageNum, pageSize, keyword, beginDate, endDate, categoryid));
	}

	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：概要为空，4：概要过长，5：内容为空，6：图片上传失败
	 */
	public void doAdd(){
		//缩略图
		UploadFile thumb = getFile("thumb");
		//分类
		int categoryid = getParaToInt("categoryid",0);
		//标题
		String title = getPara("title");
		//概要
		String describe = getPara("describe");
		//内容
		String context = getPara("link");
		//显示
		int isTop = getParaToInt("isTop",0);
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(describe)){
			renderResult(3);
			return;
		}else if(describe.length()>100){
			renderResult(4);
			return;
		}else if(StrKit.isBlank(context)){
			renderResult(5);
			return;
		}else{
			//保存
			WxArticle article = new WxArticle()
				.set("categoryid", categoryid)
				.set("title", title)
				.set("describe", describe)
				.set("isTop", isTop)
				.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("context", context);
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(thumb!=null){
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(4);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
			}
			if(service.addArticle(article)){
				renderSuccess(service.findById(article.getInt("id")));
				return;
			}
		}
		renderFailed();
	}

	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：概要为空，4：概要过长，5：内容为空，6：图片上传失败
	 */
	public void doEdit(){
		//缩略图
		UploadFile thumb = getFile("thumb");
		//ID
		String articleid = getPara("articleid");
		//分类
		int categoryid = getParaToInt("categoryid",0);
		//名称
		String title = getPara("title");
		//描述
		String describe = getPara("describe");
		//连接
		String context = getPara("link");
		//显示
		int isTop = getParaToInt("isTop",0);
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(StrKit.isBlank(articleid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(describe)){
			renderResult(3);
			return;
		}else if(describe.length()>100){
			renderResult(4);
			return;
		}else if(StrKit.isBlank(context)){
			renderResult(5);
			return;
		}else{
			//更新
			WxArticle article = new WxArticle()
				.set("id", articleid)
				.set("categoryid", categoryid)
				.set("title", title)
				.set("describe", describe)
				.set("isTop", isTop)
				.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("context", context);
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(4);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
				if(service.editArticle(article)){
					try {
						deleteFromFtp(thumbOld);
					} catch (IOException e) {
						logger.error("更新时，旧图片"+thumbOld+"删除失败！");
						e.printStackTrace();
					}
					renderSuccess(service.findById(Integer.valueOf(articleid)));
					return;
				}
			}else if(service.editArticle(article)){
				renderSuccess(service.findById(Integer.valueOf(articleid)));
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			WxArticle article = service.findById(id);
			//先判断如果上传了图片，则删除图片
			if(!StrKit.isBlank(article.getStr("thumb"))){
				try {
					deleteFromFtp(article.getStr("thumb"));
				} catch (IOException e) {
					logger.error("删除时，相关图片"+article.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
			//然后再对记录进行删除
			article.delete();
			logger.info("删除微信文章【"+id+"】，及其图片");
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 * 文本编辑中图片上传
	 */
	public void uploadimg(){
		UploadFile thumb = getFile();
		Map<String,Object> map = new HashMap<String,Object>();  
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
				map.put("error", 0);  
				map.put("url",PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));  
				renderJson(map);
		        return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);  
				map.put("message","图片上传失败");  
				renderJson(map);
			}
		}else{
			map.put("error", 1);  
			map.put("message","图片为空");  
			renderJson(map);
		}
	}
}
